package top.tenebrous.yzl.im.sender;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import top.tenebrous.yzl.im.annotation.ImProducer;
import top.tenebrous.yzl.im.contants.RedisConstants;
import top.tenebrous.yzl.im.enums.ChannelType;
import top.tenebrous.yzl.im.enums.ProducerType;

/**
 * @author yazhang6
 */
@Slf4j
@ImProducer(type = ProducerType.REDIS)
@Component
public class RedisSenderHandler implements AbstractSenderHandler{

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 接收聊天数据，进行广播，交由真正的实例进行处理
     *
     * @param session       session
     * @param message       消息
     */
    @Override
    public void broadcastMessage(WebSocketSession session, TextMessage message) {
        log.info("服务端接收到新的聊天消息:消息内容[{}]", JSON.toJSONString(message));
        String newMessage = "";
        try {
            newMessage = new String(message.getPayload().getBytes(RedisConstants.UTF8), RedisConstants.UTF8);
        } catch (Exception e) {
            log.error("sendMessageByRedis exception:", e);
        }
        // 广播
        redisTemplate.convertAndSend(ChannelType.SEND_CHANNEL.getValue(), newMessage);
    }

}
